package com.smartfactory.sail.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.smartfactory.sail.entity.Dept;
import com.smartfactory.sail.mapper.DeptMapper;
import com.smartfactory.sail.mapper.DeptPostMapper;
import com.smartfactory.sail.service.IDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartfactory.sail.vo.dept.ListDeptResp;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author 王巨壁
 * @since 2019-07-24
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {

    private DeptMapper deptMapper;
    private DeptPostMapper deptPostMapper;

    public DeptServiceImpl(DeptMapper deptMapper, DeptPostMapper deptPostMapper) {
        this.deptMapper = deptMapper;
        this.deptPostMapper = deptPostMapper;
    }

    /**
     * 获取所有部门和对应岗位信息
     *
     * @return
     */
    @Override
    public List<ListDeptResp> getAll() {
        return deptMapper.getAll();
    }

    @Transactional
    @Override
    public Long add(Dept dept) {
        if (this.save(dept)) {
            /*UpdateWrapper<Dept> update = new UpdateWrapper<>();
            update.ge("sort", dept.getSort());
            update.eq("id", dept.getId());
            update.setSql("sort = sort+1");
            this.update(update);*/
            return dept.getId();
        }
        return null;
    }

    @Transactional
    @Override
    public boolean del(Long id) {
        Dept dept = this.getById(id);
        if (dept == null) {
            return true;
        }

        if (this.removeById(id)) {
            //刪岗位
            HashMap<String, Object> map = new HashMap<>();
            map.put("deptId", dept.getId());
            deptPostMapper.deleteByMap(map);
            return true;
        }
        return false;
    }

    /**
     * 修改部门名称或者排序
     *
     * @return
     */
    @Transactional
    @Override
    public boolean updateNameOrSort(Dept dept) {
        Dept byId = this.getById(dept.getId());
        if (this.updateById(dept)) {
            if (dept.getSort() != byId.getSort()) {
                UpdateWrapper<Dept> update = new UpdateWrapper<>();
                if (dept.getSort() > byId.getSort()) {
                    //如果排序变大了. 需要把 其他between(老,新)之间的减小
                    update.setSql("sort = sort-1");
                    update.between("sort", byId.getSort(),dept.getSort());
                } else if (dept.getSort() < byId.getSort()) {
                    //如果排序变小了. 需要把 其他between(新,老)之间的减小
                    update.setSql("sort = sort+1");
                    update.between("sort", dept.getSort(), byId.getSort());
                }
                this.update(update);
                return true;
            }
        }

        return false;
    }
}
